package com.library.controller.user;


import com.library.constant.MessageConstant;
import com.library.dto.UserDTO;
import com.library.dto.UserLoginDTO;
import com.library.dto.UserPasswordDTO;
import com.library.entity.User;
import com.library.exception.CaptchaErrorException;
import com.library.exception.CaptchaHasExpiredException;
import com.library.properties.JwtProperties;
import com.library.result.Result;
import com.library.service.UserService;
import com.library.utils.JwtUtil;
import com.library.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
@Slf4j
@Api(tags = "用户模块")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private RedisTemplate redisTemplate;

    //todo 实现多种方式登录
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO, @RequestParam String captcha,
                                     @RequestParam String captchaKey ) {
        log.info("用户登录: {}", userLoginDTO);

        // 从Redis获取验证码
        String storedCaptcha = (String)redisTemplate.opsForValue().get("captcha:" + captchaKey);
        if (storedCaptcha == null) {
            throw new CaptchaHasExpiredException(MessageConstant.CAPTCHA_HAS_EXPIRED);
        }
        if (!storedCaptcha.equalsIgnoreCase(captcha)) {
            throw new CaptchaErrorException(MessageConstant.CAPTCHA_ERROR);
        }

        // 验证通过后删除Redis中的键
        redisTemplate.delete("captcha:" + captchaKey);

        User user = userService.login(userLoginDTO);

        //登录成功后，生产一个jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public Result register(@RequestBody UserDTO userDTO,@RequestParam String captcha,
                           @RequestParam String captchaKey ) {
        log.info("用户注册: {}", userDTO);

        // 从Redis获取验证码
        String storedCaptcha = (String)redisTemplate.opsForValue().get("captcha:" + captchaKey);
        if (storedCaptcha == null) {
            throw new CaptchaHasExpiredException(MessageConstant.CAPTCHA_HAS_EXPIRED);
        }
        if (!storedCaptcha.equalsIgnoreCase(captcha)) {
            throw new CaptchaErrorException(MessageConstant.CAPTCHA_ERROR);
        }

        // 验证通过后删除Redis中的键
        redisTemplate.delete("captcha:" + captchaKey);

        userService.register(userDTO);

        return Result.success();
    }

    //用户信息更改
    @PostMapping("/update")
    @ApiOperation("用户信息更改")
    public Result<String> update(@RequestBody UserDTO userDTO) {
        log.info("用户信息更改: {}", userDTO);

        userService.update(userDTO);

        return Result.success();
    }

    //修改密码
    @PostMapping("/updatePassword")
    @ApiOperation("修改密码")
    public Result<String> updatePassword(@RequestBody UserPasswordDTO userPasswordDTO,@RequestParam String captcha,
                                         @RequestParam String captchaKey) {
        log.info("修改密码: {}", userPasswordDTO);


        // 从Redis获取验证码
        String storedCaptcha = (String)redisTemplate.opsForValue().get("captcha:" + captchaKey);
        if (storedCaptcha == null) {
            throw new CaptchaHasExpiredException(MessageConstant.CAPTCHA_HAS_EXPIRED);
        }
        if (!storedCaptcha.equalsIgnoreCase(captcha)) {
            throw new CaptchaErrorException(MessageConstant.CAPTCHA_ERROR);
        }

        // 验证通过后删除Redis中的键
        redisTemplate.delete("captcha:" + captchaKey);

        userService.updatePassword(userPasswordDTO);

        return Result.success();
    }


    @PostMapping("/logout")
    @ApiOperation("用户退出")
    public Result<String> logout() {
        return Result.success();
    }




}
